<?php
namespace app\common\library;
use GatewayClient\Gateway;
use think\facade\Config;
use think\facade\Db;

class GatewayLib {
    public static function onLine($engine_name){
        $client_id = Db::name('Payload')->where('i',$engine_name)->order('t desc')->value('l');
        return  Gateway::isOnline($client_id);
    }

    /**
     * 发送信息 //开机，结算
     */
    public static function send2Client($engine_name,$data){
        $option = Config::get('gatewayworker');
        Gateway::$registerAddress = !empty($option['registerAddress']) ? $option['registerAddress'] : '127.0.0.1:1236';
        $client_id = Db::name('Payload')->where('i',$engine_name)->order('t desc')->value('l');
        $status = Gateway::isOnline($client_id);
        if($status){
            $decode = self::decode($data);
            Gateway::sendToClient($client_id,$decode);
            return ['code'=>1,'msg'=>'已推送'];
        }else{
            return ['code'=>0,'msg'=>'机器不在线'];
        }
    }
    //解析数据
    public static function decode($data){
        $m='41'.sprintf('%06X',date('H:i:s')).'00'.$data['c'];
        switch ($data['c']) {
            case '72':
                $m.='OE'.sprintf('%08X',$data['i']).sprintf('%08X',$data['u']).'0101'.sprintf('%06X',$data['y']).sprintf('%02X',$data['j']);
                # code...
                break;
            case '78':
                $m.='OC'.sprintf('%08X',$data['i']).sprintf('%08X',$data['u']).sprintf('%08X','11');
                break;
            default:
                # code...
                break;
        }

        return ['code'=>1,'data'=>$m];
    }
}